﻿using System.Collections;
using System.Text.RegularExpressions;

namespace Art_To_Eagle.Lib.Safebooru
{
    class PostList
    {
        const string PageUrl = "https://safebooru.donmai.us/posts?page=";

        public static Post[] Get(int page = 1)
        {
            var html = Utils.HttpGet(PageUrl + page);

            var list = new ArrayList();

            foreach (Match match in Regex.Matches(html, "<article.+?\n</article>"))
            {
                var post = new Post();
                //懒得研究怎么只返回内容数据了所以干脆分割字符串吧（
                var s = Regex.Match(match.Value, @"data-id=""\d+?""").Value;
                int.TryParse(s.Substring(9, s.Length - 10), out post.Id);
                s = Regex.Match(match.Value, @"data-tags="".+?""").Value;
                var tags = s.Substring(11, s.Length - 12).Split(' ');
                for (int i = 0; i < tags.Length; i++)
                    tags[i] = tags[i].Replace("_", " ");
                post.Tags = tags;
                s = Regex.Match(match.Value, @"data-source="".+?""").Value;
                post.SourceUrl = s.Substring(13, s.Length - 14);
                s = Regex.Match(match.Value, @"data-normalized-source="".+?""").Value;
                post.FromPage = s.Substring(24, s.Length - 25);
                s = Regex.Match(match.Value, @"data-file-url="".+?""").Value;
                post.FileUrl = s.Substring(15, s.Length - 16);
                s = Regex.Match(match.Value, @"data-preview-file-url="".+?""").Value;
                post.PreviewImage = s.Substring(23, s.Length - 24);
                list.Add(post);
            }
            return (Post[])list.ToArray(typeof(Post));
        }
    }
}
